package com.lyssoft.learning;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.security.KeyStore;
import java.util.Scanner;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

public class EchoSSLClient {
    public static void main(String[] args) throws Exception {
        String keystorePath = "src/main/resources/cert.jks";
        String keystorePass = "123456";
        
        KeyStore keyStore = KeyStore.getInstance("JKS");
        try (InputStream ksStream = new FileInputStream(keystorePath)) {
            keyStore.load(ksStream, keystorePass.toCharArray());
        }
        
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
        tmf.init(keyStore);
        
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);
        
        Socket clientSocket = context.getSocketFactory().createSocket();
        clientSocket.connect(new InetSocketAddress("127.0.0.1", 8443));
        
        try (PrintWriter writer  = new PrintWriter(new OutputStreamWriter(
                clientSocket.getOutputStream(), "UTF-8"));
                Scanner scanner = new Scanner(System.in)) {
            
            String line;
            while ((line = scanner.nextLine()) != null && !"exit".equalsIgnoreCase(line)) {
                writer.println(line);
                writer.flush();
            }
        }
        
        clientSocket.close();
    }
}
